import http from '@/common/http';
import Loading from '@/components/loading';
var MQTT = require('paho-mqtt');
const defaultMqttState = () => {
  return {
    mqtt: null,
    mqttConfig: null,
    subscribeList: []
  };
};
const state = defaultMqttState();
const getters = {
  mqttConfig(state) {
    return state.mqttConfig;
  },
  mqttClient(state) {
    return state.mqtt;
  },
  mqttConnected(state) {
    if (state.mqtt) {
      return state.mqtt.isConnected();
    } else {
      return false;
    }
  }
};
const actions = {
  getMqttConfig(context) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('pakj/common/getMqttMsg').then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setMqttConfig', res.data.data);
          resolve();
        } else {
          reject(new Error(res.data.msg));
        }
      });
    });
  },
  initMqttClient(context, config) {
    return new Promise((resolve, reject) => {
      let mqttClient = new MQTT.Client(
        config.host,
        config.port,
        config.clientId
      );
      mqttClient.connect({
        useSSL: config.useSSL,
        userName: config.username,
        password: config.password,
        cleanSession: true,
        onSuccess: () => {
          context.commit('setMqttClient', mqttClient);
          resolve();
        },
        onFailure: () => {
          console.error('MQTT连接失败');
          reject(new Error('MQTT连接失败'));
        }
      });
    });
  },
  subscribe(context, topic) {
    return new Promise((resolve, reject) => {
      if (context.state.mqtt) {
        if (context.state.subscribeList.indexOf(topic) === -1) {
          context.state.mqtt.subscribe(topic, {
            qos: 0,
            onSuccess: () => {
              context.state.subscribeList.push(topic);
              console.log('MQTT成功订阅了：', topic);
              resolve();
            },
            onFailure: () => {
              reject(new Error(topic + '订阅失败'));
            }
          });
        } else {
          reject(new Error(topic + '已经订阅了'));
          context.actions.unsubscribe(topic).then(() => {
            context.actions.subscribe(topic);
          });
        }
      } else {
        reject(new Error('MQTT没有初始化'));
      }
    });
  },
  unsubscribe(context, topic) {
    return new Promise((resolve, reject) => {
      if (context.state.mqtt) {
        if (context.state.subscribeList.indexOf(topic) > -1) {
          context.state.mqtt.unsubscribe(topic, {
            onSuccess: () => {
              context.state.subscribeList.splice(
                context.state.subscribeList.indexOf(topic),
                1
              );
              resolve();
            },
            onFailure: () => {
              reject(new Error(topic + '退订失败'));
            }
          });
        } else {
          reject(new Error(topic + '没有订阅，无法退订'));
        }
      } else {
        reject(new Error('MQTT没有初始化'));
      }
    });
  }
};
const mutations = {
  resetMqtt(state) {
    Object.assign(state, defaultMqttState());
  },
  setMqttConfig(state, config) {
    config.port = 443;
    config.useSSL = true;
    console.info('MQTT配置信息：', config);
    state.mqttConfig = config;
  },
  setMqttClient(state, client) {
    state.mqtt = client;
  },
  sendMqttMessage(state, data) {
    if (state.mqtt) {
      let message = new MQTT.Message(data.msg);
      message.destinationName = data.topic;
      message.qos = 0;
      state.mqtt.send(message);
      console.info('MQTT已发送出消息：', message);
    }
  },
  closeMqtt(state) {
    if (state.mqtt) {
      state.mqtt.disconnect();
      state.mqtt = null;
      state.subscribeList = [];
    }
  }
};
export default {
  state,
  actions,
  getters,
  mutations
};
